package com.ruoyi.system.service.impl;

import java.util.List;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ADataMapper;
import com.ruoyi.system.domain.AData;
import com.ruoyi.system.service.IADataService;

/**
 * 素材库类别Service业务层处理
 *
 * @author gf
 * @date 2024-10-21
 */
@Service
public class ADataServiceImpl implements IADataService {
    @Autowired
    private ADataMapper aDataMapper;

    /**
     * 查询素材库类别
     *
     * @param id 素材库类别主键
     * @return 素材库类别
     */
    @Override
    public AData selectADataById(Long id) {
        return aDataMapper.selectADataById(id);
    }

    /**
     * 查询素材库类别列表
     *
     * @param aData 素材库类别
     * @return 素材库类别
     */
    @Override
    public List<AData> selectADataList(AData aData) {
        return aDataMapper.selectADataList(aData);
    }

    /**
     * 新增素材库类别
     *
     * @param aData 素材库类别
     * @return 结果
     */
    @Override
    public int insertAData(AData aData) {
        aData.setCreateTime(DateUtils.getNowDate());
        boolean flag = !aData.getParentId().equals(0L);
        AData info = aDataMapper.selectADataById(aData.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (flag && info == null && !UserConstants.DEPT_NORMAL.equals(info.getIsShow()))
        {
            throw new ServiceException("分类停用，不允许新增");
        }
        String ancestors = "";
        if(null != info){
            ancestors = info.getAncestors() + ",";
        }
        aData.setAncestors(ancestors + aData.getParentId());
        return aDataMapper.insertAData(aData);
    }

    /**
     * 修改素材库类别
     *
     * @param aData 素材库类别
     * @return 结果
     */
    @Override
    public int updateAData(AData aData) {
        aData.setUpdateTime(DateUtils.getNowDate());
        AData newParentCategory = aDataMapper.selectADataById(aData.getParentId());
        AData oldCategory = aDataMapper.selectADataById(aData.getId());
        if (StringUtils.isNotNull(newParentCategory) && StringUtils.isNotNull(oldCategory))
        {
            String newAncestors = newParentCategory.getAncestors() + "," + newParentCategory.getId();
            String oldAncestors = oldCategory.getAncestors();
            aData.setAncestors(newAncestors);
            updateADataChildren(aData.getId(), newAncestors, oldAncestors);
        }
        int result = aDataMapper.updateAData(aData);
        if (UserConstants.DEPT_NORMAL.equals(aData.getIsShow()) && StringUtils.isNotEmpty(aData.getAncestors())
                && !StringUtils.equals("0", aData.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentCategoryStatusNormal(aData);
        }
        return result;
    }

    /**
     * 批量删除素材库类别
     *
     * @param ids 需要删除的素材库类别主键
     * @return 结果
     */
    @Override
    public int deleteADataByIds(Long[] ids) {
        return aDataMapper.deleteADataByIds(ids);
    }

    /**
     * 删除素材库类别信息
     *
     * @param id 素材库类别主键
     * @return 结果
     */
    @Override
    public int deleteADataById(Long id) {
        return aDataMapper.deleteADataById(id);
    }

    /**
     * 批量逻辑删除素材库类别
     *
     * @param ids 需要删除的素材库类别主键
     * @return 结果
     */
    @Override
    public int logicDeleteADataByIds(Long[] ids) {
        return aDataMapper.logicDeleteADataByIds(ids);
    }
    /**
     * 逻辑删除素材库类别信息
     *
     * @param id 素材库类别主键
     * @return 结果
     */
    @Override
    public int logicDeleteADataById(Long id) {
        return aDataMapper.logicDeleteADataById(id);
    }

    /**
     * 校验名称是否唯一
     *
     * @param aData 分类信息
     * @return 结果
     */
    @Override
    public boolean checkNameUnique(AData aData) {
        Long id = StringUtils.isNull(aData.getId()) ? -1L : aData.getId();
        AData info = aDataMapper.checkNameUnique(aData.getDataName(), aData.getParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 根据ID查询所有子分类（正常状态）
     *
     * @param categoryId 分类ID
     * @return 子分类数
     */
    @Override
    public int selectNormalChildrenCategoryById(Long categoryId) {
        return aDataMapper.selectNormalChildrenCategoryById(categoryId);
    }

    /**
     * 修改该分类的父级分类状态
     *
     * @param aData 当前分类
     */
    private void updateParentCategoryStatusNormal(AData aData) {
        String ancestors = aData.getAncestors();
        Long[] ids = Convert.toLongArray(ancestors);
        aDataMapper.updateCategoryStatusNormal(ids);
    }

    /**
     * 修改子元素关系
     *
     * @param categoryId 被修改的分类ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateADataChildren(Long categoryId, String newAncestors, String oldAncestors)
    {
        List<AData> children = aDataMapper.selectChildrenById(categoryId);
        for (AData child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            aDataMapper.updateCategoryChildren(children);
        }
    }
}
